<template>
  <div>
    <NavBar />
    <div class="search-container">
      <div class="search-box">
        <el-input v-model="searchQuery" placeholder="请输入搜索关键词" class="search-input"></el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>
    </div>
    <PostList :posts="posts" />
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import axiosInstance from '../plugins/axios' // 导入 axios 实例
import NavBar from '../components/NavBar.vue'
import PostList from '../components/PostList.vue'

const searchQuery = ref('')
const posts = ref([])

const handleSearch = () => {
  console.log('Search query:', searchQuery.value)
  fetchSearchResults(searchQuery.value)
}

const fetchSearchResults = async (query: string) => {
  try {
    const response = await axiosInstance.get('/posts/search', {
      params: { keyword: query }
    })
    posts.value = response.data
  } catch (error) {
    console.error('Error fetching search results:', error)
  }
}
</script>

<style scoped>
.search-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20px 0;
}

.search-box {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}
</style>